package com.solution.wx.share.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.entity.ProductImageEntity;
import com.solution.admin.product.entity.ProductPriceEntity;
import com.solution.admin.product.entity.ProductPropertyRelaEntity;
import com.solution.admin.product.entity.ProductSpecRelaEntity;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductImageService;
import com.solution.admin.product.service.ProductPropertyRelaService;
import com.solution.admin.product.service.ProductService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.ip.IPUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.service.OrderEvaluationService;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.share.constants.ShareConstants.COMMENT_STATUS;
import com.solution.wx.share.constants.ShareConstants.COMMENT_TYPE;
import com.solution.wx.share.constants.ShareConstants.SHARE_TYPE;
import com.solution.wx.share.entity.ShareCommentEntity;
import com.solution.wx.share.entity.ShareInfoEntity;
import com.solution.wx.share.entity.ShareListVO;
import com.solution.wx.share.service.ShareCommentService;
import com.solution.wx.share.service.ShareInfoService;

/**
 * 潮品社区搜索控制层
 * @author xkl
 * @date 2018年5月3日 下午7:16:49
 */
@RequestMapping("/wx/share")
@Controller
public class ShareInfoSearchController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(ShareInfoSearchController.class);

	@Autowired
	private ShareInfoService shareInfoService;

	@Autowired
	private ShareCommentService shareCommentService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProductImageService productImageService;

	@Autowired
	private ProductCategoryService productCategoryService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ProductPropertyRelaService productPropertyRelaService;

	@Autowired
	private OrderEvaluationService orderEvaluationService;

	/**
	 * 潮品社区列表查询
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月3日 下午7:21:10
	 */
	@RequestMapping("/search")
	public String listShareInfoPage(HttpServletRequest request, HttpServletResponse response) {
		PageParam pageParam = getPageParam(request);
		//		pageParam.setNumPerPage(6);
		String searchKey = request.getParameter("searchKey");
		String requestType = request.getParameter("requestType");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("searchKey", searchKey);
		param.put("shareType", SHARE_TYPE.PRODUCT.getCode());
		try {
			PageBean shareInfoPage = shareInfoService.listShareInfoPage(pageParam, param);
			//检查用户是否对该分析内容点赞
			for (int i = 0; i < shareInfoPage.getRecordList().size(); i++) {
				ShareInfoEntity shareInfoEntity = (ShareInfoEntity)shareInfoPage.getRecordList().get(i);
				Integer isUserLike = shareInfoService.isUserLike(shareInfoEntity.getId(), getCustomerId()) > 0 ? 1 : 0;
				shareInfoEntity.setIsUserLike(isUserLike);
			}
			// 如果是异步，直接写response
			if("sync".equals(requestType)){
				try {
					response.getWriter().write(JSONObject.toJSON(shareInfoPage).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("pageBean", shareInfoPage);
			request.setAttribute("requestType", requestType);
			request.setAttribute("searchKey", searchKey);
		} catch (Exception e) {
			handleException("查询分享信息失败", logger, e);
		}
		return "wx/share/share_list";
	}

	/**
	 * 潮品社区点赞
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月5日 下午4:10:55
	 */
	@RequestMapping("/doShareInfoLike")
	@ResponseBody
	public Map<String, Object> doShareInfoLike(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Long shareId = Long.parseLong(request.getParameter("shareId"));
			// 0 代表隐名用户
			Long customerId = 0L;
			if(isLogin(request)){
				customerId = getCustomerId();
			}
			//检查用户是否对该分享内容点赞过
			Long isUserLike = shareInfoService.isUserLike(shareId, customerId);
			if (isUserLike > 0) {
				resultMap.put(PublicStatus.RESULT_CODE, "-1");
				resultMap.put(PublicStatus.RESULT_MSG, "已点赞");
				return resultMap;
			}
			//对分享内容点赞
			shareInfoService.doShareInfoLike(shareId, customerId);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("点赞失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 潮品详情
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月7日 下午3:13:42
	 */
	@RequestMapping("/detail")
	public String shareInfoDetail(HttpServletRequest request){
		//查询参数
		Map<String, Object> param = new  HashMap<String, Object>();
		//查询分享信息详情
		ShareInfoEntity shareInfo = null;
		String uuid = request.getParameter("uuid");
		String id = request.getParameter("id");
		if (StringUtil.isNotNull(uuid)) {
			shareInfo = shareInfoService.getShareInfoByUUID(uuid);
		} else if (StringUtil.isNotNull(id)) {
			shareInfo = shareInfoService.getShareInfoById(Long.parseLong(id));
		} else {
			request.setAttribute("errMessage", "查询异常");
			return "/wx/wx_error";
		}
		//判断用户是否点赞或收藏
		Integer isUserLike = shareInfoService.isUserLike(shareInfo.getId(), getCustomerId()) > 0 ? 1 : 0;
		Integer isUserFavorite = shareInfoService.isUserFavorite(shareInfo.getId(), getCustomerId()) > 0 ? 1 : 0;
		shareInfo.setIsUserLike(isUserLike);
		shareInfo.setIsUserFavorite(isUserFavorite);
		request.setAttribute("shareInfo", shareInfo);

		/**
		 * 查询3条评论信息
		PageParam pageParam = new PageParam(1, 3);
		param.put("shareId", shareInfo.getId());
		param.put("parentCommentId", 0);
		param.put("deleteFlag", 1);
		param.put("commentStatus", 2);
		PageBean commentPage = shareCommentService.listShareCommentPageWithReply(pageParam, param);
		for (int i = 0; i < commentPage.getRecordList().size(); i++) {
			ShareCommentEntity commentEntity = (ShareCommentEntity)commentPage.getRecordList().get(i);
			Integer isUserCommentLike = shareCommentService.isUserCommentLike(commentEntity.getId(), getCustomerId()) > 0 ? 1 : 0;
			commentEntity.setIsUserLike(isUserCommentLike);
		}
		request.setAttribute("shareCommentPage", commentPage);
		 */

		// 商品查询参数
		param = new  HashMap<String, Object>();
		// 【1】查询商品基本信息
		Long productId = shareInfo.getSharedProductId();
		String productCode = request.getParameter("productCode");
		ProductEntity product = null;
		if(StringUtil.isNotNull(productId)) {
			param.put("productId", productId);
			product = productService.getProductById(productId);
		} else if(null == productId && StringUtil.isNotNull(productCode)) {
			product = productService.getProductByCode(productCode);
			productId = product.getId();
			param.put("productId", productId);
		} else {
			// 没有ID,没有CODE，就返回空的商品对象
			product = new ProductEntity();
		}
		Map<String, Object> productDetailMap = new HashMap<String, Object>();
		/**
		 * key-object
		 * product_info 商品基本信息
		 * product_price 商品所有价格
		 * product_spec 商品规格
		 * product_composition 商品规格项组合
		 * product_property 商品详情属性
		 * produt_image 商品图片
		 * product_comment 商品评论
		 */
		// BigDecimal basePrice = product.getBasePrice();
		// 商品基本信息和详情
		productDetailMap.put("product_info", product);

		// 主商品价格 = 基价 + 客户差价
		BigDecimal productPrice = product.getBasePrice();
		BigDecimal marketProductPrice = product.getMarketPrice();

		// 【2】查询商品所有价格
		List<ProductPriceEntity> ppeList = productService.getProductPriceList(productId);
		productDetailMap.put("product_price", ppeList);
		String customerLevel = getCustomerLevel();
		if (isLogin(request)) {
			if (ppeList != null && ppeList.size() > 0) {
				for (ProductPriceEntity ppe : ppeList) {
					// 只取对应级别的价格
					if (ppe.getPriceLevel().equals(customerLevel)) {
						productPrice = productPrice.add(ppe.getDiffPrice());
						marketProductPrice = marketProductPrice.add(ppe.getDiffPrice());
					}
				}
			}
		} else {
			// 匿名用户 显示游客价 和 市场价 + 对应的默认规格价格
			productPrice = (null != product.getTouristPrice()) ? product.getTouristPrice() : BigDecimal.ZERO;
			marketProductPrice = (null != product.getMarketPrice()) ? product.getMarketPrice() : BigDecimal.ZERO;
		}

		// 【3】查询商品规格(包裹规格项的名称、值、价格)
		// 商品默认规格的价格
		BigDecimal defaultSpecPrice = new BigDecimal(0);
		List<ProductSpecRelaEntity> productSpecList = productService.listProductSpecPriceByProductId(param);
		if(productSpecList != null && productSpecList.size() > 0){
			for (ProductSpecRelaEntity productSpec : productSpecList) {
				if(StringUtil.isNotEmpty(productSpec.getProductSpecListStr())){
					List<ProductSpecRelaEntity> tmpSpecList = JSONArray.parseArray("["+productSpec.getProductSpecListStr()+"]", ProductSpecRelaEntity.class);
					productSpec.setProductSpecList(tmpSpecList);
					if(tmpSpecList != null && tmpSpecList.size() > 0){
						defaultSpecPrice = defaultSpecPrice.add(tmpSpecList.get(0).getSpecPrice());
					}
				}
			}
		}
		// 主商品价格
		request.setAttribute("mainProductPrice", productPrice);
		// 商品价格  基价+级别差价+默认规格价格
		request.setAttribute("productPrice", productPrice.add(defaultSpecPrice));
		productDetailMap.put("product_spec", productSpecList);
		request.setAttribute("hasSpec", productSpecList.size() > 0 ? "true":"false");

		// 【6】查询商品图片
		List<ProductImageEntity> productImageList = productImageService.listProductImageForProductDetail(productId);
		if(productImageList != null && productImageList.size() > 0){
			for (ProductImageEntity productImage : productImageList) {
				if(1 == productImage.getImageType()){
					// 主图
					productDetailMap.put("product_main_image", productImage.getImagePath());
				}
			}
		}
		productDetailMap.put("product_image", productImageList);

		//查询商品属性
		List<ProductPropertyRelaEntity> productPropertyList = productPropertyRelaService.listProductPropertyRela(product.getId());
		productDetailMap.put("productPropertyList", productPropertyList);
		// 商品详情
		request.setAttribute("productDetailMap", productDetailMap);


		// 查询商品评论
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("productCode", product.getProductCode());
		paramMap.put("isDelete", 1);
		PageParam pageParam = new PageParam(1, 5);
		PageBean evaluationPage = orderEvaluationService.listOrderEvaluationPage(pageParam, paramMap);
		request.setAttribute("evaluationPage", evaluationPage);

		// 查询微信调用接口信息
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));

		//PV UV统计,登录用户使用customerId统计UV,未登录用户使用IP统计
		if (isLogin(request)) {
			shareInfoService.doShareInfoPVUV(shareInfo.getId(), getCustomer().getId().toString());
			shareInfoService.doShareProductPVUV(product.getId(), getCustomer().getId().toString());
		} else {
			String ip = IPUtils.getIntenetIP(request);
			shareInfoService.doShareInfoPVUV(shareInfo.getId(), ip);
			shareInfoService.doShareProductPVUV(product.getId(), ip);
		}
		//分享用的uuid
		request.setAttribute("uuid", UUID.randomUUID().toString());
		request.setAttribute("isLogin", isLogin(request)?"1":"0");

		//通过sessionID记录访问用户的推荐人,查询用户取用户的推荐码
		CustomerEntity shareCustomer = customerService.getCustomerById(shareInfo.getShareUserId());
		shareInfoService.doRecordInvitation(request.getSession().getId(), shareCustomer.getInvitationCode());
		return "wx/share/share_detail";
	}

	/**
	 * 分享后回调
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月9日 下午3:54:36
	 */
	@RequestMapping("/doShareInfoShared")
	@ResponseBody
	public Map<String, Object> doShareInfoShared(HttpServletRequest request){
		//被分享的潮品
		String shareId = request.getParameter("shareId");
		//分享后产生的新潮品uuid
		String uuid = request.getParameter("uuid");
		//被分享的商品ID
		Long productId = Long.parseLong(request.getParameter("productId"));
		String shareUrl = "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Fshare%2Fdetail%3Fuuid%3D"+uuid;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		//uuid与shareId都不存在
		if (!StringUtil.isNotNull(shareId) && !StringUtil.isNotNull(uuid)) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			return resultMap;
		}
		
		try {
			ShareInfoEntity shareInfo = null;
			//被分享的潮品分享数+1(分享商品时无shareId)
			if (StringUtil.isNotNull(shareId)) {
				shareInfoService.doShareInfoShared(Long.parseLong(shareId));
			}
			//获取uuid对应的分享
			if (StringUtil.isNotNull(uuid)) {
				shareInfo = shareInfoService.getShareInfoByUUID(uuid);
				//如果该uuid的分享对象存在则表示是多次分享,只记录分享次数,不创建新的分享信息
				if (null != shareInfo) {
					shareInfoService.doShareInfoShared(shareInfo.getId());
					shareInfoService.doShareProductRecord(productId);
					resultMap.put(PublicStatus.RESULT_CODE, "1");
					resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
					return resultMap;
				}
			}

			//创建新的分享信息
			shareInfo = new ShareInfoEntity();
			ProductEntity product = productService.getProductById(productId);
			//给分享人创建一条新的潮品分享记录
			ProductCategoryEntity productCategory = productCategoryService.getProductCategoryById(product.getProductCategoryId());
			CustomerEntity customer = getCustomer();
			shareInfo.setShareUserId(customer.getId());
			shareInfo.setWxOpenId(customer.getOpenId());
			shareInfo.setWxHeadImage(customer.getHeadImage());
			shareInfo.setShareType(SHARE_TYPE.PRODUCT.getCode());
			shareInfo.setSharedProductId(product.getId());
			shareInfo.setSharedModuleId(null);
			shareInfo.setShareTitle(product.getProductName());
			shareInfo.setProductCode(product.getProductCode());
			shareInfo.setProductCategoryName(productCategory.getCategoryNamePath().replace("|", "/"));
			shareInfo.setSharedProductImagePath(product.getProductImgPath());
			shareInfo.setShareDesc(product.getProductName());
			shareInfo.setShareDesc(product.getProductTitle());
			shareInfo.setUuid(uuid);
			shareInfo.setShareUrl(shareUrl);
			shareInfo.setShareDataUrl(shareUrl);
			shareInfo.setShareStatus(PublicStatus.STATUS.ENABLED.getId());
			shareInfo.setReferralCode(customer.getInvitationCode());
			shareInfoService.saveShareInfo(shareInfo);
			//记录商品分享次数
			shareInfoService.doShareProductRecord(productId);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("分享失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 潮品评论页面
	 * @param request
	 * @param response
	 * @return String
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年5月9日 下午2:57:42
	 */
	@RequestMapping("/wxShareCommentPage")
	public String toWxCommentPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			// 同步异步请求标志(异步请求，返回json数据通过response.getWirter().write 刷入页面)
			String requestType = request.getParameter("requestType");
			String pageNumStr = request.getParameter("pageNum");
			if(StringUtil.isEmpty(pageNumStr)){
				pageNumStr = "1";
			}
			int pageNum = Integer.parseInt(pageNumStr);
			int numPerPage = 4;
			PageParam pageParam = super.getPageParam(request);
			pageParam.setPageNum(pageNum);
			pageParam.setNumPerPage(numPerPage);
			// 分享潮品ID
			String shareId = request.getParameter("shareId");
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("shareId", shareId);
			paramMap.put("customerId", getCustomerId());
			/* 分页 */
			PageBean pageBean = shareCommentService.listShowCommentPage(pageParam, paramMap);
			// 如果是异步，直接写response
			if("sync".equals(requestType)){
				try {
					response.getWriter().write(JSONObject.toJSON(pageBean).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ShareInfoEntity shareInfo = shareInfoService.getShareInteraction(shareId);
			model.addAttribute("shareId", shareId);
			model.addAttribute("commentQuantity", shareInfo.getCommentQuantity());
			model.addAttribute("commentList", pageBean.getRecordList());
			model.addAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/wx/share/comment_list";
	}

	/**
	 * 发布评论
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月9日 下午5:20:47
	 */
	@RequestMapping("/publishShareComment")
	@ResponseBody
	public Map<String, Object> publishShareComment(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long shareId = Long.parseLong(request.getParameter("shareId"));
		Long parentCommentId = Long.parseLong(request.getParameter("parentCommentId"));
		String parentCommentName = request.getParameter("parentCommentName");
		String commentContent = request.getParameter("commentContent");
		CustomerEntity customer = getCustomer();
		try {
			//评论内容检查
			if (StringUtil.isEmpty(commentContent)) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "必须填写评论内容");
				return resultMap;
			}
			if (commentContent.length() > 300) {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "评论内容最多300字");
				return resultMap;
			}
			//回复对象判断(如果是回复他人还要确定是回复谁的)
			if (!parentCommentId.equals(0L)) {
				StringBuffer commentContentStr = new StringBuffer();
				commentContentStr.append("回复 ")
				.append(parentCommentName)
				.append(" :")
				.append(commentContent);
				commentContent = commentContentStr.toString();
			}
			ShareCommentEntity shareComment = new ShareCommentEntity();
			String commentCode = DateUtils.getDate("yyyyMMddHHmmss")+String.valueOf(System.currentTimeMillis()).substring(3);
			shareComment.setShareId(shareId);
			shareComment.setParentCommentId(parentCommentId);
			shareComment.setCommentContent(commentContent);
			shareComment.setCommentCode(commentCode);
			shareComment.setCommentCustomerId(customer.getId());
			shareComment.setCommentUserHeadImage(customer.getHeadImage());
			shareComment.setCommentNickname(customer.getUserName());
			shareComment.setCommentType(parentCommentId == 0 ? 
					COMMENT_TYPE.COMMENT_SHARE.getCode() : COMMENT_TYPE.COMMENT_REPLY.getCode());
			shareComment.setCommentStatus(COMMENT_STATUS.APPROVE_PASS.getCode());
			shareCommentService.saveShareComment(shareComment);
			shareInfoService.doShareInfoComment(shareId);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("发布评论失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 分享评论点赞
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月9日 下午5:53:11
	 */
	@RequestMapping("/doShareCommentLike")
	@ResponseBody
	public Map<String, Object> doShareCommentLike(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Long commentId = Long.parseLong(request.getParameter("commentId"));
			Long customerId = getCustomerId();
			//检查用户是否对该评论点赞过
			Long isUserLike = shareCommentService.isUserCommentLike(commentId, getCustomerId());
			if (isUserLike > 0) {
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "已点赞");
				return resultMap;
			}
			//对评论点赞
			shareCommentService.doShareCommentLike(commentId, customerId);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("评论点赞失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 潮品收藏
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月14日 下午3:54:35
	 */
	@RequestMapping("/doShareInfoFavorite")
	@ResponseBody
	public Map<String, Object> doShareInfoFavorite(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Long shareId = Long.parseLong(request.getParameter("shareId"));
			Long customerId = getCustomerId();
			//检查用户是否收藏过
			Long isUserFavorite = shareInfoService.isUserFavorite(shareId, customerId);
			if (isUserFavorite > 0) {
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "已收藏");
				return resultMap;
			}
			//用户收藏
			Long id = shareInfoService.doShareInfoFavorite(shareId, customerId);
			resultMap.put("favoriteId", id);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("潮品收藏失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 取消收藏
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年6月12日 上午10:01:03
	 */
	@RequestMapping("/removeShareInfoFavorite")
	@ResponseBody
	public Map<String, Object> removeShareInfoFavorite(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Long shareId = Long.parseLong(request.getParameter("shareId"));
			Long customerId = getCustomerId();
			//用户取消收藏
			int count = shareInfoService.removeShareInfoFavorite(shareId, customerId);
			if (count > 0) {
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
			} else {
				resultMap.put(PublicStatus.RESULT_CODE, "0");
				resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			}
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("潮品收藏失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 分享模块后回调
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年6月12日 下午5:11:31
	 */
	@RequestMapping("/doShareModuleShared")
	@ResponseBody
	public Map<String, Object> doShareModuleShared(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String uuid = request.getParameter("uuid");
		String shareTitle = request.getParameter("shareTitle");
		String shreDesc = request.getParameter("shareDesc");
		String imagePath = request.getParameter("imagePath");
		List<String> productIdList = Lists.newArrayList(request.getParameter("productIds")
				.substring(1, request.getParameter("productIds").length()-1)
				.split(","));
		String shareModuleUrl = "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Fshare%2Fmodule%3Fuuid%3D"+uuid;
		if (StringUtil.isNotNull(uuid)) {
			//获取uuid对应的分享
			ShareInfoEntity shareModuleInfo = shareInfoService.getShareInfoByUUID(uuid);
			if (null != shareModuleInfo) {
				//同页面二次分享,直接返回操作成功
				resultMap.put(PublicStatus.RESULT_CODE, "1");
				resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
				return resultMap;
			}
		}
		try {
			CustomerEntity customer = getCustomer();
			ShareInfoEntity shareModuleInfo = new ShareInfoEntity();
			shareModuleInfo.setShareUserId(customer.getId());
			shareModuleInfo.setWxOpenId(customer.getOpenId());
			shareModuleInfo.setWxHeadImage(customer.getHeadImage());
			shareModuleInfo.setShareType(SHARE_TYPE.MODULE.getCode());
			shareModuleInfo.setSharedProductId(null);
			shareModuleInfo.setSharedModuleId(null);
			shareModuleInfo.setShareTitle(shareTitle);
			shareModuleInfo.setProductCode(null);
			shareModuleInfo.setProductCategoryName(null);
			shareModuleInfo.setSharedProductImagePath(imagePath);
			shareModuleInfo.setShareDesc(shreDesc);
			shareModuleInfo.setUuid(uuid);
			shareModuleInfo.setShareUrl(shareModuleUrl);
			shareModuleInfo.setShareDataUrl(shareModuleUrl);
			shareModuleInfo.setShareStatus(PublicStatus.STATUS.ENABLED.getId());
			shareModuleInfo.setReferralCode(customer.getInvitationCode());

			//获取分享的所有商品
			Map<Long, ProductEntity> productMap = productService.listProductMapByIds(productIdList);

			//获取所有商品的分类
			List<Long> categoryIds = new ArrayList<Long>();
			for (Map.Entry<Long, ProductEntity> product : productMap.entrySet()) {
				categoryIds.add(product.getValue().getProductCategoryId());
			}
			Map<String, ProductCategoryEntity> productCategoryMap = productCategoryService.listProductCategoryByIds(categoryIds);

			List<ShareInfoEntity> shareInfoList = new ArrayList<ShareInfoEntity>();
			//前台获取的productId可能会出现重复或不存在,因此以查询后的商品结果为准
			for (Long productId : productMap.keySet()) {
				ProductEntity product = productMap.get(productId);
				String productUuid = UUID.randomUUID().toString();
				String productUrl = "/wx/my/toBindAccountPage?goToUrl=%2Fwx%2Fshare%2Fdetail%3Fuuid%3D"+uuid;
				ShareInfoEntity shareInfo = new ShareInfoEntity();
				shareInfo.setShareUserId(shareModuleInfo.getShareUserId());
				shareInfo.setWxOpenId(shareModuleInfo.getWxOpenId());
				shareInfo.setWxHeadImage(shareModuleInfo.getWxHeadImage());
				shareInfo.setShareType(SHARE_TYPE.PRODUCT.getCode());
				shareInfo.setSharedProductId(product.getId());
				shareInfo.setShareTitle(product.getProductName());
				shareInfo.setProductCode(product.getProductCode());
				shareInfo.setProductCategoryName(productCategoryMap
						.get(product.getProductCategoryId())
						.getCategoryNamePath()
						.replace("|", "/"));
				shareInfo.setSharedProductImagePath(product.getProductImgPath());
				shareInfo.setShareDesc(product.getProductName());
				shareInfo.setUuid(productUuid);
				shareInfo.setShareUrl(productUrl);
				shareInfo.setShareDataUrl(productUrl);
				shareInfo.setShareStatus(PublicStatus.STATUS.ENABLED.getId());
				shareInfo.setReferralCode(customer.getInvitationCode());
				shareInfoList.add(shareInfo);
				//记录商品分享次数
				shareInfoService.doShareProductRecord(productId);
			}
			shareInfoService.saveShareModuleList(shareModuleInfo, shareInfoList);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("分享模块失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 潮品社区模块分享查询
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月3日 下午7:21:10
	 */
	@RequestMapping("/module")
	public String listShareModulePage(HttpServletRequest request, HttpServletResponse response) {
		// 返回页面结果
		ShareListVO result = new ShareListVO();
		PageParam pageParam = getPageParam(request);
		pageParam.setNumPerPage(Integer.MAX_VALUE);
		String moduleId = request.getParameter("moduleId");
		String uuid = request.getParameter("uuid");
		String searchKey = request.getParameter("searchKey");
		String requestType = request.getParameter("requestType");

		//参数
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtil.isNotNull(uuid)) {
			//如果是uuid则需要置换为moduleId
			ShareInfoEntity moduleInfo = shareInfoService.getShareInfoByUUID(uuid);
			result.setShareInfo(moduleInfo);
			param.put("sharedModuleId", moduleInfo.getId());
			moduleId = moduleInfo.getId().toString();
		} else if (StringUtil.isNotNull(moduleId)) {
			param.put("sharedModuleId", moduleId);
		} else {
			request.setAttribute("errMessage", "查询异常");
			return "/wx/wx_error";
		}
		param.put("searchKey", searchKey);
		param.put("shareType", SHARE_TYPE.PRODUCT.getCode());
		try {
			List<Long> productIdsList = new ArrayList<Long>();
			PageBean shareInfoPage = shareInfoService.listShareInfoPage(pageParam, param);
			List<ShareInfoEntity> shareList = (List)shareInfoPage.getRecordList();
			//检查用户是否对该分析内容点赞
			for (ShareInfoEntity shareInfoEntity : shareList) {
				Integer isUserLike = shareInfoService.isUserLike(shareInfoEntity.getId(), getCustomerId()) > 0 ? 1 : 0;
				shareInfoEntity.setIsUserLike(isUserLike);
				productIdsList.add(shareInfoEntity.getSharedProductId());
			}

			// 查询商品
			if(productIdsList.size() > 0){
				param.put("ids", productIdsList);
				param.put("isLogin", isLogin(request)?"1":"0");
				if(isLogin(request)){
					param.put("customerId", getCustomerId());
					param.put("customerLevel", getCustomerLevel());
				}
				List<ProductEntity> productList = productService.listProductForSiteItem(param);
				// 初始化价格
				productService.initProductDefaultSpecPrice(productList);
				// 格式化价格
				formatProductPrice(productList);
				// 放入map和分享记录对象 
				Map<Long, ProductEntity> productMap = new HashMap<Long, ProductEntity>();
				if(productList != null && productList.size() > 0){
					for (ProductEntity product : productList) {
						productMap.put(product.getId(), product);
					}
					result.setProductMap(productMap);
				}

				// 未登录的时，过滤掉游客不可见的商品
				List lastShareInfoList = new ArrayList();
				for (ShareInfoEntity shareInfoEntity : shareList) {
					if(productMap.containsKey(shareInfoEntity.getSharedProductId())){
						lastShareInfoList.add(shareInfoEntity);
					}
				}
				shareInfoPage.setRecordList(lastShareInfoList);
				shareInfoPage.setTotalCount(lastShareInfoList.size());
			}

			result.setIsLogin(isLogin(request) ? "1" : "0");
			result.setShareList(shareInfoPage);

			request.setAttribute("shareData", result);


			// 如果是异步，直接写response
			if("sync".equals(requestType)){
				try {
					response.getWriter().write(JSONObject.toJSON(result).toString());
					response.getWriter().flush();
					response.getWriter().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			request.setAttribute("pageBean", shareInfoPage);
			request.setAttribute("requestType", requestType);
			request.setAttribute("searchKey", searchKey);
			request.setAttribute("moduleId", moduleId);
		} catch (Exception e) {
			handleException("查询分享信息失败", logger, e);
		}
		return "wx/share/share_module_list";
	}


	/**
	 * 格式化商品价格
	 * @param productList
	 */
	private void formatProductPrice(List<ProductEntity> productList){
		// 初始化价格显示
		DecimalFormat df = new DecimalFormat("#.00");
		if(productList != null && productList.size() > 0){
			for (ProductEntity product : productList) {
				if(product.getProductPrice() != null){
					String[] prices = df.format(product.getProductPrice()).split("\\.");
					product.setProductPriceInteger(prices[0]);
					product.setProductPriceDecimal(prices[1]);
				}
			}
		}
	}

	/**
	 * 查询评论的所有回复
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年6月14日 下午4:49:26
	 */
	@RequestMapping("/listAllReply")
	@ResponseBody
	public Map<String, Object> listAllReply(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String commentId = request.getParameter("commentId");
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("parentCommentId", commentId);
			List<ShareCommentEntity> replyList = shareCommentService.listShareComment(paramMap);
			resultMap.put("replyList", replyList);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
			resultMap.put(PublicStatus.RESULT_MSG, "操作成功");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
			handleException("查询评论回复失败", logger, e);
		}
		return resultMap;
	}
}
